<template>
  <div class="acceptance-form">
    <form class="custom-form">
      <input type="file" ref="fileInput" @change="handleFileSelect" accept="image/*" style="display: none">
      <div class="form-item">
      <span>验 收 单 ：</span>
      <button @click="selectFile">添加文件</button>
    </div>
      <div v-if="selectedFile" class="mt-3">
        <img :src="imageUrl" alt="预览图" class="preview-image">
        <button class="btn btn-success mt-2" @click="uploadFile">开始识别</button>
      </div>
      <div v-if="result" class="result-area mt-4">
      </div>
<!--      <div class="form-item">-->
<!--        <span>项目名称：</span>-->
<!--        <input class="input" type="text" v-model="form.projectName" placeholder="请输入项目名称">-->
<!--      </div>-->
      <el-form-item label="项目名称">
          <el-input v-model="form.projectName" placeholder="请输入项目名称"></el-input>
      </el-form-item>
<!--      <div class="form-item">-->
<!--        <span>项目编号：</span>-->
<!--        <input class="input" v-model="form.projectNo" placeholder="请输入项目编号">-->
<!--      </div>-->
      <el-form-item label="项目编号">
        <el-input v-model="form.projectNo" placeholder="请输入项目编号"></el-input>
      </el-form-item>
<!--      <div class="form-item">-->
<!--        <span>使用单位：</span>-->
<!--        <select class="input" v-model="form.useDepartment">-->
<!--          <option value="">请选择使用单位</option>-->
<!--          <option v-for="dept in usedepartments" :key="dept.depId" :value="dept.department">-->
<!--            {{ dept.department }}-->
<!--          </option>-->
<!--        </select>-->
<!--      </div>-->
      <el-form-item label="使用单位">
        <el-select
            v-model="form.useDepartment"
            filterable
            allow-create
            placeholder="请选择或输入使用单位"
            class="input"
        >
          <el-option
              v-for="dept in usedepartments"
              :key="dept.depId"
              :label="dept.department"
              :value="dept.department"
          />
        </el-select>
      </el-form-item>
<!--      <div class="form-item">-->
<!--        <span>施工单位：</span>-->
<!--        <select class="input" v-model="form.doDepartment">-->
<!--          <option value="">请选择施工单位</option>-->
<!--          <option v-for="dept in doDepartments" :key="dept.depId" :value="dept.department">-->
<!--            {{ dept.department }}-->
<!--          </option>-->
<!--        </select>-->
<!--      </div>-->
      <el-form-item label="施工单位">
        <el-select
            v-model="form.doDepartment"
            filterable
            allow-create
            placeholder="请选择或输入施工单位"
            class="input"
        >
          <el-option
              v-for="dept in doDepartments"
              :key="dept.depId"
              :label="dept.department"
              :value="dept.department"
          />
        </el-select>
      </el-form-item>
<!--      <div class="form-item">-->
<!--        <span>监督单位：</span>-->
<!--        <select class="input" v-model="form.seeDepartment">-->
<!--          <option value="">请选择监督单位</option>-->
<!--          <option v-for="dept in seeDepartments" :key="dept.depId" :value="dept.department">-->
<!--            {{ dept.department }}-->
<!--          </option>-->
<!--        </select>-->
<!--      </div>-->
      <el-form-item label="监督单位">
        <el-select
            v-model="form.seeDepartment"
            filterable
            allow-create
            placeholder="请选择或输入监督单位"
            class="input"
        >
          <el-option
              v-for="dept in seeDepartments"
              :key="dept.depId"
              :label="dept.department"
              :value="dept.department"
          />
        </el-select>
      </el-form-item>

      <button class="submit_btn" @click.prevent="submitForm">提交</button>
    </form>
  </div>
</template>

<script>
import {addForm} from "@/js/Form.js";
import {HandleJson} from "@/js/json.js";
import {getListDeptByType} from "@/js/Dept.js";
import {addDept} from "@/js/Dept.js";
import {v4 as uuidv4} from "uuid";
import {ElMessage} from "element-plus";

export default {
  created() {
    // 在组件创建时加载所有部门列表
    this.getListDepartmentByUse();
    this.getListDepartmentByDo();
    this.getListDepartmentBySee();
  },
  data() {
    return {
      form:{
        projectName: '',
        projectNo: '',
        useDepartment: '',
        doDepartment:'',
        seeDepartment:''
      },
      usedepartments: [],
      doDepartments: [],
      seeDepartments: [],
      newDepartments: [], // 存储新添加的部门，等待提交时一起添加到数据库
      jsonInput:'',
      selectedFile: null,
      imageUrl: '',
      result: '',
      resultInfo:[
        {
          name:'content',
          value:''
        },{
        name:'height',
        value:''
        },{
          name:'width',
          value:''
        },{
          name:'orgheight',
          value:''
        },{
          name:'orgwidth',
          value:''
        },{
          name:'prism_wnum',
          value:''
        },{
          name:'prism_wordsInfo',
          value:[
            {
              name:'direction',
              value:''
            },
            {
              name:'height',
              value:''
            },
            {
              name:'width',
              value:''
            },
            {
              name:'prob',
              value:''
            },
            {
              name:'word',
              value:''
            },
            {
              name:'pos',
              value:[
                {
                  //1
                  name:'x1',
                  value:''
                },
                {
                //2
                  name:'y1',
                  value:''
                },{
                //3
                  name:'x2',
                  value:''
                },{
                //4
                  name:'y2',
                  value:''
                },{
                  name:'x3',
                  value:''
                },{
                  name:'y3',
                  value:''
                },{
                  name:'x4',
                  value:''
                },{
                  name:'y4',
                  value:''
                }
              ]
            },
          ]
        }
      ],
      resultWordsInfo:[]
    }
  },
  methods:{
    
    // 获取使用部门列表
    getListDepartmentByUse() {
      if (this.usedepartments.length === 0) { // 避免重复请求
        getListDeptByType("使用")
            .then(response => {
              console.log('获取使用部门成功:', response);
              if (response && Array.isArray(response)) {
                this.usedepartments = response;
                if (response.length > 0) {
                  this.form.useDepartment = response[0].department || ''; // 默认选中第一个
                }
              } else {
                console.error('获取使用部门失败: 返回数据格式不正确', response);
              }
            })
            .catch(error => {
              console.error('获取使用部门出错:', error);
            });
      }
    },
    // 获取施工部门列表
    getListDepartmentByDo() {
      if (this.doDepartments.length === 0) { // 避免重复请求
        getListDeptByType("施工")
            .then(response => {
              console.log('获取施工部门成功:', response);
              if (response && Array.isArray(response)) {
                this.doDepartments = response;
                if (response.length > 0) {
                  this.form.doDepartment = response[0].department || ''; // 默认选中第一个
                }
              } else {
                console.error('获取施工部门失败: 返回数据格式不正确', response);
              }
            })
            .catch(error => {
              console.error('获取施工部门出错:', error);
            });
      }
    },
    // 获取施工部门列表
    getListDepartmentBySee() {
      if (this.seeDepartments.length === 0) { // 避免重复请求
        getListDeptByType("监督")
            .then(response => {
              console.log('获取监督部门成功:', response);
              if (response && Array.isArray(response)) {
                this.seeDepartments = response;
                if (response.length > 0) {
                  this.form.seeDepartment = response[0].department || ''; // 默认选中第一个
                }
              } else {
                console.error('获取监督部门失败: 返回数据格式不正确', response);
              }
            })
            .catch(error => {
              console.error('获取监督部门出错:', error);
            });
      }
    },
    selectFile() {
      this.$refs.fileInput.click();
    },
    handleFileSelect(event) {
      const file = event.target.files[0];
      if (file) {
        this.selectedFile = file;
        this.imageUrl = URL.createObjectURL(file);
      }
    },
    uploadFile() {
      const formData = new FormData();
      formData.append('file', this.selectedFile);

      fetch('/api/ocr/recognize', {
        method: 'POST',
        body: formData
      })
      .then(response => response.json())
      .then(data => {
        this.result = data;
        console.log('OCR识别结果:', this.result);
        
        // 处理OCR结果并提取表单字段
        this.extractFormFields(data);
        
        // 使用修复后的HandleJson函数处理数据
        this.resultInfo = HandleJson(this.result);
      })
      .catch(error => {
        console.error('Error:', error);
        this.result = '上传失败: ' + error.message;
      });
    },
    
    // 从OCR结果中提取表单字段
    extractFormFields(ocrResult) {
      if (!ocrResult || !ocrResult.prism_wordsInfo) return;
      
      const wordsInfo = ocrResult.prism_wordsInfo;
      
      // 提取项目名称
      this.extractAndFillField(wordsInfo, '项目名称', 'projectName');

      // 提取项目编号
      this.extractAndFillField(wordsInfo, '项目编号', 'projectNo');

      // 提取使用单位
      this.extractAndFillField(wordsInfo, '使用单位', 'useDepartment');

      // 提取施工单位
      this.extractAndFillField(wordsInfo, '施工单位', 'doDepartment');

      // 提取监督单位
      this.extractAndFillField(wordsInfo, '监督单位', 'seeDepartment');
    },

    // 提取字段并填充到表单
    extractAndFillField(wordsInfo, labelText, formField) {
      // 找到标签的索引
      const labelIndex = wordsInfo.findIndex(item => item.word === labelText);
      if (labelIndex === -1 || labelIndex >= wordsInfo.length - 1) return;

      // 获取标签后面的值
      const value = wordsInfo[labelIndex + 1].word;
      if (!value) return;

      console.log(`设置${labelText}为: ${value}`);
      
      // 根据字段类型处理不同的表单元素
      if (formField === 'useDepartment') {
        this.handleDepartmentSelection(value, 'usedepartments', formField);
      } else if (formField === 'doDepartment') {
        this.handleDepartmentSelection(value, 'doDepartments', formField);
      } else if (formField === 'seeDepartment') {
        this.handleDepartmentSelection(value, 'seeDepartments', formField);
      } else {
        // 直接更新Vue数据模型
        this.form[formField] = value;
      }
    },
    
    // 处理部门选择
    handleDepartmentSelection(value, departmentListName, formField) {
      // 检查部门列表是否已加载
      if (this[departmentListName].length === 0) {
        console.log(`${departmentListName}尚未加载，等待加载完成后设置值`);
        
        // 设置一个定时器，等待部门列表加载完成
        const checkInterval = setInterval(() => {
          if (this[departmentListName].length > 0) {
            clearInterval(checkInterval);
            this.setDepartmentValue(value, departmentListName, formField);
          }
        }, 100);
        
        // 设置超时，避免无限等待
        setTimeout(() => {
          clearInterval(checkInterval);
          console.log(`等待${departmentListName}加载超时，直接设置值`);
          this.form[formField] = value;
        }, 5000);
      } else {
        this.setDepartmentValue(value, departmentListName, formField);
      }
    },
    
    // 设置部门值
    setDepartmentValue(value, departmentListName, formField) {
      // 检查值是否在列表中
      const found = this[departmentListName].some(dept => dept.department === value);
      
      if (found) {
        // 如果值在列表中，直接设置
        this.form[formField] = value;
      } else {
        ElMessage.error(`"${value}"不在部门列表中`+"无法识别部门")

        // 设置表单字段值，使下拉框选中该值
        this.form[formField] = value;
      }
    },

    
    // 提交表单
    submitForm() {
      // 表单验证
      if (!this.form.projectName) {
        ElMessage.warning('请输入项目名称');
        return;
      }
      if (!this.form.projectNo) {
        ElMessage.warning('请输入项目编号');
        return;
      }
      if (!this.form.useDepartment) {
        ElMessage.warning('请选择使用单位');
        return;
      }
      if (!this.form.doDepartment) {
        ElMessage.warning('请选择施工单位');
        return;
      }
      if (!this.form.seeDepartment) {
        ElMessage.warning('请选择监督单位');
      }
      //如果部门在数据库中没有，提示重新输入或者选择部门。否则实现下面的方法。
      Promise.all([
        getListDeptByType('使用'),
        getListDeptByType('施工'),
        getListDeptByType('监督')
      ]).then(([useDepts, doDepts, seeDepts]) => {
        const useExists = useDepts.some(dept => dept.department === this.form.useDepartment);
        const doExists = doDepts.some(dept => dept.department === this.form.doDepartment);
        const seeExists = seeDepts.some(dept => dept.department === this.form.seeDepartment);
        
        if (!useExists || !doExists || !seeExists) {
          let missingDepts = [];
          if (!useExists) missingDepts.push('使用单位');
          if (!doExists) missingDepts.push('施工单位');
          if (!seeExists) missingDepts.push('监督单位');
          
          ElMessage.warning(`${missingDepts.join('、')}不存在，请重新输入或选择部门`);
        } else {
          this.submitFormToServer();
        }
      }).catch(error => {
        console.error('检查部门存在性失败:', error);
        ElMessage.error('检查部门失败: ' + error.message);
      });

    },
    
    // 将表单提交到服务器
    submitFormToServer() {
      // 由于没有formId，我们可以传null或生成一个临时ID
      const tempFormId = uuidv4();
      addForm(
        tempFormId,                // formId
        this.form.projectName,     // formName
        this.form.projectNo,       // formNum
        this.form.useDepartment,   // useDep
        this.form.doDepartment,    // workDep
        this.form.seeDepartment    // overseeDep
      )
      .then(response => {
        console.log('表单提交成功:', response);
        console.log('提交表单数据:', this.form);
        ElMessage.success('表单提交成功！');

        // 提交成功后重置表单
        this.resetForm();
      })
      .catch(error => {
        console.error('表单提交失败:', error);
        ElMessage.error('表单提交失败: ' + (error.response?.data?.message || error.message));
      });
    },
    
    // 重置表单
    resetForm() {
      this.form.projectName = '';
      this.form.projectNo = '';
      this.form.useDepartment = '';
      this.form.doDepartment = '';
      this.form.seeDepartment = '';
    }
    }
}

</script>

<style scoped>
.acceptance-form {
  width: 100%;
  max-height: 700px;
  overflow-y: auto;
  overflow-x: hidden;
  padding: 10px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
}
.form-item {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}
.form-item >span{
font-weight: bold;
}
.custom-form{
  margin-top: 20px;
  display: flex;
  flex-direction: column;
  margin-bottom: 16px;
}
.input{
  display: flex;
  align-items: center;
  width: 60%;
  height: 40px;
  background-color: #fff;
  border-radius: 8px;
  margin-bottom: 20px;
  padding: 0 10px;
}
.submit_btn{
  width: 100%;
  max-width: 400px;
  height: 44px;
  background-color: #28a745;
  color: #fff;
  font-size: 16px;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  margin-bottom: 20px;
}
.preview-image {
  max-width: 100%;
  max-height: 400px;
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 5px;
}
</style>